package com.yunjian.core.admin;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunjian.common.utils.*;
import com.yunjian.core.dto.AccountDto;
import com.yunjian.core.dto.OrderRespDto;
import com.yunjian.core.entity.Account;
import com.yunjian.core.entity.SysUserEntity;
import com.yunjian.core.entity.SysUserRoleEntity;
import com.yunjian.core.service.IAccountService;
import com.yunjian.core.service.IPurchaseOrderService;
import com.yunjian.core.service.SysUserRoleService;
import com.yunjian.core.service.SysUserService;
import io.swagger.annotations.Api;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xiapengyu
 * @since 2020-01-29
 */

@Api("用户管理api")
@RestController
@RequestMapping("/sys/account")
public class SysAccountController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAccountService accountService;
    @Autowired
    private IPurchaseOrderService purchaseOrderService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 分页查询用户列表
     */
    @PostMapping("/list")
    public R list(@RequestBody Map<String, Object> params) {
        logger.info("分页查询用户列表{}", JsonUtil.toJsonString(params));
        PageUtils page = accountService.queryAccountByPage(params);
        if (page != null) {
            return R.ok().put("page", page);
        } else {
            return R.error("分页查询用户列表失败");
        }
    }

    /**
     * 所有用户列表
     */
    @PostMapping("/queryTotalAccount")
    public R queryTotalAccount() {
        logger.info("所有用户列表");
        try {
            SysUserEntity user = HttpContextUtils.getLoginSysUserEntity();
            logger.info("当前登录用户{}", JsonUtil.toJsonString(user));
            SysUserRoleEntity role = sysUserRoleService.getOne(new QueryWrapper<SysUserRoleEntity>()
                    .eq("user_id", user.getUserId()));

            QueryWrapper<Account> query = new QueryWrapper<Account>();
            query.eq("delete_flag", 1).orderByDesc("create_time");
            SysUserEntity loginUser = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
            if (role != null && role.getRoleId().intValue() != Constant.SUPER_ADMIN && role.getRoleId().intValue() != Constant.SUPER_DEALER) {
                query.eq("dealer_id", loginUser.getUserId().intValue());
            }
            /*if (loginUser.getUserId() != Constant.SUPER_ADMIN) {
                query.eq("dealer_id", loginUser.getUserId().intValue());
            }*/
            List<Account> list = accountService.list(query);
            return R.ok().put("accountList", list);
        } catch (Exception e) {
            logger.error("查询用户列表失败", e);
            return R.error("查询用户列表失败");
        }
    }

    /**
     * 删除用户
     */
    @PostMapping("/deleteAccount")
    public R deleteAccount(@RequestBody Map<String, Object> params) {
        logger.info("删除用户{}", JsonUtil.toJsonString(params));
        String id = StringUtil.obj2String(params.get("id"));
        if (!StringUtils.isEmpty(id)) {
            accountService.remove(new QueryWrapper<Account>().eq("id", id));
            return R.ok();
        } else {
            return R.error("参数错误");
        }
    }

    /**
     * 查询用户详情
     */
    @PostMapping("/queryAccountInfo")
    public R queryAccountInfo(@RequestBody Map<String, Object> params) {
        logger.info("查询用户详情{}", JsonUtil.toJsonString(params));
        String id = StringUtil.obj2String(params.get("id"));
        if (!StringUtils.isEmpty(id)) {
            Account account = accountService.getOne(new QueryWrapper<Account>().eq("id", id));
            SysUserEntity user = userService.getOne(new QueryWrapper<SysUserEntity>().eq("user_id", account.getDealerId()));
            AccountDto record = new AccountDto();
            BeanUtils.copyProperties(account, record);
            record.setDealerName(user.getUsername());

            //查询经销商列表
            List<SysUserRoleEntity> list = sysUserRoleService.list(new QueryWrapper<SysUserRoleEntity>()
                    .ne("role_id", Constant.SUPER_ADMIN));
            List<Long> userIds = new ArrayList<>();
            list.forEach(item -> {
                userIds.add(item.getUserId());
            });

            int isAdmin = 0;
            SysUserEntity loginUser = HttpContextUtils.getLoginSysUserEntity();
            SysUserRoleEntity userRoleEntity = sysUserRoleService.getOne(new QueryWrapper<SysUserRoleEntity>()
                    .eq("user_id", loginUser.getUserId()));
            if (userRoleEntity.getRoleId().intValue() == Constant.SUPER_ADMIN
                    || userRoleEntity.getRoleId().intValue() == Constant.SUPER_DEALER) {
                isAdmin = 1;
            }

            List<SysUserEntity> dealList = userService.list(new QueryWrapper<SysUserEntity>()
                    .in("user_id", userIds).eq("delete_flag", 1));

            return R.ok().put("account", record).put("dealList", dealList).put("isAdmin", isAdmin);
        } else {
            return R.error("参数错误");
        }
    }

    /**
     * 保存用户信息
     */
    @PostMapping("/saveAccount")
    public R saveAccount(@RequestBody Map<String, Object> params) {
        logger.info("保存用户信息{}", JsonUtil.toJsonString(params));
        return accountService.saveAccount(params);
    }

    /**
     * 分页查询客户采购需求列表
     */
    @PostMapping("/queryAccountOrderList")
    public R queryAccountOrderList(@RequestBody Map<String, Object> params) {
        logger.info("分页查询客户采购需求列表{}", JsonUtil.toJsonString(params));
        PageUtils page = purchaseOrderService.queryAccountOrderList(params);
        return R.ok().put("page", page);
    }

    /**
     * 查询客户采购需求单详情
     */
    @PostMapping("/queryOrderInfo")
    public R queryOrderDetail(@RequestBody Map<String, Object> params) {
        logger.info("查询客户采购需求单详情{}", JsonUtil.toJsonString(params));
        String orderNo = StringUtil.obj2String(params.get("orderNo"));
        OrderRespDto info = purchaseOrderService.queryOrderInfo(orderNo);
        return R.ok().put("order", info);
    }

}
